package com.jiyinit.web.core.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.web.core.business.dao.TabCoreOrgDao;
import com.jiyinit.web.core.business.dao.TabCoreUserDao;
import com.jiyinit.web.core.business.dao.TabCoreUserRoleDao;
import com.jiyinit.web.core.business.dao.TabLoginUserDao;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.entity.TabLoginInfoEntity;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.LoginUserVo;
import com.jiyinit.web.core.common.vo.MobileUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * <p>权限拦截器</p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author changly
 * @version 1.0
 * @date 2017/11/28 17:37
 * @since 1.0
 */
public class MobileInterceptor extends HandlerInterceptorAdapter {

    @Resource(name = "login.tabLoginUserDao")
    private TabLoginUserDao tabLoginUserDao;

    @Resource(name = "core.tabCoreUserDao")
    private TabCoreUserDao tabCoreUserDao;

    @Resource(name = "core.tabCoreUserRoleDao")
    private TabCoreUserRoleDao tabCoreUserRoleDao;

    @Resource(name = "core.tabCoreOrgDao")
    private TabCoreOrgDao tabCoreOrgDao;

    // 用于创建MultipartHttpServletRequest,Txd添加
    @Resource(name = "multipartResolver")
    private MultipartResolver multipartResolver;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String logJson = getRequestJson(request);
        if(Check.isNullStrStrict(logJson))return false;
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);

        if(loginUserVo == null) return false;
        if(loginUserVo.getToken() == null || "".equals( loginUserVo.getToken())) {
            PrintWriter write =  response.getWriter();
            write.print("token不能为空");
            return false;
        }
        if(loginUserVo.getUserId() == null ) {
            PrintWriter write =  response.getWriter();
            write.print("userId不能为空");
            return false;
        }

        //根据用户ID查询token
        TabLoginInfoEntity entity =  tabLoginUserDao.getLoginInfoByUserId(loginUserVo.getUserId());
        if(entity == null ) {
            PrintWriter write =  response.getWriter();
            write.print("用户不存在登录信息");
            return false;
        }
        //比较
        if(!loginUserVo.getToken().equals(entity.getToken())){
            PrintWriter write =  response.getWriter();
            //write.print("已在其它的设备登录");
            write.print(JSON.toJSONString(ResponseDto.responseFail(ResponseDto.FAILED,"已在其它的设备登录")));
           return false;
        }

        //用户信息，部门，信息 放session
        MobileUserVo vo=UserUtil.getMobileUser(loginUserVo.getToken());
        if(null==vo)  //session中不存在
        {

            TabCoreUserEntity userBean= tabCoreUserDao.getUserInfoById(loginUserVo.getUserId());
            TabCoreOrgEntity orgBean=null;
            if(null!=userBean)
            {
                orgBean= tabCoreOrgDao.selectById(userBean.getOrgId());
                vo=new MobileUserVo();
                vo.setLoginName(userBean.getUserName());
                vo.setUserId(userBean.getUserId());
                vo.setOrgId(userBean.getOrgId());
                vo.setOrgName(orgBean.getOrgName());
                vo.setLevel(new Integer(userBean.getLevel()));
                //存入sesson中
                UserUtil.setMobileUserSession(vo,loginUserVo.getToken());
            }

        }
        return super.preHandle(request, response, handler);
    }

    /**
     * 获取 requestJson
     * @param req
     * @return
     */
    private String getRequestJson(ServletRequest req){
        String enctype = req.getContentType();
        StringBuffer sbf = new StringBuffer("{");
        if (StringUtils.isNotBlank(enctype) && enctype.contains("multipart/form-data")){
            MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart((HttpServletRequest) req);
            Map<String, String[]> map = multipartRequest.getParameterMap();
            boolean isFirst = true;
            for(String key : map.keySet()){
                if(isFirst) {
                    sbf.append("\""+key+"\" : \""+map.get(key)[0]+"\"");
                    isFirst = false;
                }else{
                    sbf.append(",\""+key+"\" : \""+map.get(key)[0]+"\"");
                }
            }
            sbf.append("}");
            String str = sbf.toString();
            return str;
            // 返回 MultipartHttpServletRequest 用于获取 multipart/form-data 方式提交的请求中 上传的参数
            //return multipartResolver.resolveMultipart((HttpServletRequest) req);
        }else{
            HttpServletRequest request = (HttpServletRequest) req;
            String request_json = request.getParameter("request_json");
            return request_json;
        }
    }

}
